<template>
  <el-row>
    <basic-container>
      <div class="block">
        <el-row>
          <span class="demonstration">日期范围:  </span>
          <el-date-picker
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="dateTimerRange"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator=" 至 "
            start-placeholder="开始日期 "
            end-placeholder=" 结束日期"
            align="right">
          </el-date-picker>
          <el-button type="primary" @click.native="searchDataRange">查询</el-button>
        </el-row>
      </div>
      <div>
        <el-card>
          <div id="myChartOnlineLine"  ref="myChart" style="height: 400px;"></div>
        </el-card>
      </div>
    </basic-container>
    <basic-container>
      <avue-crud :option="optionTable"
                 :search.sync="search"
                 :data="dataTable"
                 ref="crud"
                 :page.sync="page"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
      >
      </avue-crud>
    </basic-container>
  </el-row>
</template>

<script>
  import {getList,getAcquisitionOnLine} from "@/api/stress/history";
  import {dateFormat} from "@/util/date";

  export default {
    data() {
      return {
        //表格
        search:{},
        initFlag: true,
        selectionList: [],
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        optionTable: {
          height: '430px',
          calcHeight: 80,
          tip: false,
          border: true,
          index: true,
          addBtn: false,
          refreshBtn: false,
          showColumn: false,
          columnBtn: false,
          menu: false,
          column: [
            {
              label: "采集时间",
              prop: "startTime",
            },
            {
              label: "采集数值",
              prop: "sampleValue"
            },
            {
              label: "单位",
              prop: "sampleUnit",
              value: "Hz"
            }
          ]
        },
        dataTable: [],
        //图表数据设置
        pageLine: {
          pageSize: 500,
          currentPage: 1,
          total: 0
        },
        //图表设置
        upColor:'#ec0000',
        upBorderColor: '#8A0000',
        downColor: '#00da3c',
        downBorderColor: '#008F28',
        lineOption:{
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            }
          },
          grid: {
            left: '10%',
            right: '10%',
            bottom: '15%'
          },
          xAxis: {
            type: 'category',
            data: [],
            // data: ['2013/1/24','2013/1/25','2013/1/26','2013/1/27',
            //   '2013/1/28','2013/1/29','2013/1/30','2013/1/31'],
            scale: true,
            boundaryGap: false,
            axisLine: {onZero: false},
            splitLine: {show: false},
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax'
          },
          yAxis: {
            scale: true,
            splitArea: {
              show: true
            }
          },
          dataZoom: [
            {
              type: 'inside',
              start: 50,
              end: 100
            },
            {
              show: true,
              type: 'slider',
              top: '90%',
              start: 50,
              end: 100
            }
          ],
          series: [
            {
              name: '应力',
              type: 'line',
              data: [],
              // data: [2320.26,2320.26,2287.3,2362.94,
              //   2300,2291.3,2288.26,2308.38],
              smooth: true,
              lineStyle: {
                opacity: 0.5
              }
            }
          ]
        },
        //查询
        positionId: '',
        sampleType: 4,
        //时间查询
        dateTimerRange:[],
        pickerOptions: {
          shortcuts: [{
            text: '最近一天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近二天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近三天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }

      };
    },
    watch:{
      //观察option的变化
      lineOption: {
        handler(newVal, oldVal) {
          if (this.myChart) {
            if (newVal) {
              this.myChart.setOption(newVal);
            } else {
              this.myChart.setOption(oldVal);
            }
          } else {
            this.drawHistoryLine();
          }
        },
        deep: true //对象内部属性的监听，关键。
      }
    },
    created() {
      this.dateCreated();
      this.initData();
    },
    computed: {
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    mounted() {
      this.drawHistoryLine();
      //this.initData();
    },
    methods: {
      dateCreated() {
        //当前设定的日期时间
        this.dateTimerRange.push(dateFormat(new Date()))
        //前一天设定的日期时间
        let d = new Date
        d.setTime(d.getTime()-24*60*60*1000);
        this.dateTimerRange.unshift(dateFormat(d))
      },
      initData() {
        this.positionId = this.$route.params.id;
        this.handlePositionDetail();
      },
      drawHistoryLine(){
        if (document.getElementById('myChartOnlineLine') == null) {
          return
        }
        this.$echarts.dispose(document.getElementById('myChartOnlineLine'))
        let myChartOnlineLine = this.$echarts.init(document.getElementById('myChartOnlineLine'))// 基于准备好的dom，初始化echarts实例
        myChartOnlineLine.setOption(this.lineOption,true);// 绘制图表
      },
      drawLineInit(){
          this.$nextTick(() => {
            this.drawHistoryLine()
        })
      },
      handlePositionDetail(){
        let params = {}
        if (this.dateTimerRange) {
          params = {
            startTime_datege: this.dateTimerRange[0],
            startTime_datelt: this.dateTimerRange[1],
            positionId: this.positionId,
            sampleType: this.sampleType
          };
        }else {
          params = {
            positionId: this.positionId,
            sampleType: this.sampleType
          };
        }
        //曲线
        this.handleAcquisitionOnLine(this.pageLine,params);
        //表格
        this.onLoad(this.page,params)
      },
      async handleAcquisitionOnLine(page,params = {}){
        let records = []
        let pages = 0
        await getAcquisitionOnLine(page.currentPage, page.pageSize,params).then(res => {
          //this.splitData(res.data.data.records)
          const rec = res.data.data.records
          for (let j = 0; j< rec.length; j++) {
            records.push(rec[j])
          }
          pages = res.data.data.pages

        })
        if (pages > 1){
          for (let i = 2; i < pages +1; i++) {
            await getAcquisitionOnLine(i, page.pageSize,params).then(res => {
              const reco = res.data.data.records
              for (let k = 0; k< reco.length; k++) {
                records.push(reco[k])
              }
            })
          }
        }
        await this.splitData(records)

      },
      splitData(rawData) {
        let categoryData = [];
        let values = []
        for (let i = 0; i < rawData.length; i++) {
          categoryData.push(rawData[i].startTime);
          values.push(rawData[i].sampleValue);
        }
        this.lineOption.xAxis.data = categoryData
        this.lineOption.series[0].data = values
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
        let values = {};
        if (this.dateTimerRange) {
          values = {
            startTime_datege: this.dateTimerRange[0],
            startTime_datelt: this.dateTimerRange[1],
            positionId: this.positionId,
            sampleType: this.sampleType
          };
        }else {
          values = {
            positionId: this.positionId,
            sampleType: this.sampleType
          };
        }
        //表格
        this.onLoad(this.page,values)
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.dataTable = data.records;
          this.loading = false;
        });
      },
      searchData(values){
        //曲线
        this.handleAcquisitionOnLine(this.pageLine,values);
        //表格
        this.onLoad(this.page,values)
      },
      searchDataRange(){
        let values = {};
        if (this.dateTimerRange) {
          values = {
            startTime_datege: this.dateTimerRange[0],
            startTime_datelt: this.dateTimerRange[1],
            positionId: this.positionId,
            sampleType: this.sampleType
          };
        }else {
          values = {
            positionId: this.positionId,
            sampleType: this.sampleType
          };
        }

        this.searchData(values)
      }
    }
  };
</script>

<style>
  .box {
    height: 800px;
  }

  .el-scrollbar {
    height: 100%;
  }

  .box .el-scrollbar__wrap {
    overflow: scroll;
  }
</style>
